#include "arpa/inet.h"
#include "netinet/in.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/socket.h"
#include "unistd.h"

#define oops(m) \
  {             \
    perror(m);  \
    exit(1);    \
  }

int main(int ac, char *av[]) {
  if (ac != 3) {
    fprintf(stderr, "usage: %s ip filename\n", *av);
    exit(1);
  }

  // step 1: get a socket
  int sock_id = socket(AF_INET, SOCK_STREAM, 0);
  if (sock_id == -1) {
    oops("socket");
  }

  // step 2: connect to server
  struct sockaddr_in servadd;
  memset(&servadd, 0, sizeof(servadd));
  servadd.sin_family = AF_INET;
  servadd.sin_port = htons(15000);
  servadd.sin_addr.s_addr = inet_addr(av[1]);

  if (connect(sock_id, (struct sockaddr *)&servadd, sizeof(servadd)) != 0) {
    oops("connect");
  }

  // step 3: send directory name, then read back results
  if (write(sock_id, av[2], strlen(av[2])) == -1) {
    oops("write");
  }
  if (write(sock_id, "\n", 1) == -1) {
    oops("write");
  }

  char buf[BUFSIZ];
  int n_read;
  while ((n_read = read(sock_id, buf, BUFSIZ)) > 0) {
    if (write(1, buf, n_read) == -1) {
      oops("write");
    }
  }

  close(sock_id);

  return 0;
}